package com.xhwl.centiotdata.suppliersystem.dahuaIcc;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.amazonaws.services.kms.model.KMSInvalidStateException;
import com.xhwl.centiotdata.integration.IntegrationCategoryEnum;
import com.xhwl.centiotdata.pojo.constant.DaHuaIccConstant;
import com.xhwl.centiotdata.pojo.dto.dahua.SecurityDaHuaDTO;
import com.xhwl.centiotdata.pojo.dto.dahua.UserDaHuaDTO;
import com.xhwl.centiotdata.pojo.dto.dahua.UserDaHuaIccDTO;
import com.xhwl.centiotdata.pojo.dto.dahua.VisitorInfoDaHuaDTO;
import com.xhwl.centiotdata.pojo.dto.visitor.VisitorIntegrationConfigDTO;
import com.xhwl.centiotdata.utils.LocalDateTimeUtils;
import com.xhwl.common.dto.cent.visitor.VisitorAuthDTO;
import com.xhwl.common.dto.cent.visitor.VisitorInfoDTO;
import com.xhwl.common.dto.cent.visitor.VisitorOpenDTO;
import com.xhwl.common.enums.CodeEnum;
import com.xhwl.common.enums.CredentialsEnum;
import com.xhwl.common.enums.visitor.VisitorStatusEnum;
import com.xhwl.common.exception.BusinessException;
import com.xhwl.common.pojo.ResultJson;
import com.xhwl.common.pojo.cent.auth.AuthAccountMapping;
import com.xhwl.common.pojo.cent.sdata.Account;
import com.xhwl.common.pojo.cent.visitor.Follower;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: yanyixiong
 * @Description:大华ICC 访客对接
 * @Date: create in 15:05 2022/3/4
 */
@Slf4j
@Service
public class VisitorDaHuaIccHandler {
    @Autowired
    private GeneralDaHuaIccHandler generalDaHuaIccHandler;

    public AuthAccountMapping createUser(VisitorIntegrationConfigDTO configDTO, UserDaHuaIccDTO userDaHuaDTO) {
        Map<String, Object> params = JSONObject.parseObject(JSONObject.toJSONString(userDaHuaDTO), Map.class);
        JSONObject resultObject = generalDaHuaIccHandler.post(DaHuaIccConstant.CREATE_USER_URL, params, configDTO.getProjectId(), configDTO.getProductId(), configDTO.getIpAndPort(), configDTO.getLoginName(), configDTO.getPassword(), configDTO.getAk(), configDTO.getSk());
        if (resultObject == null || !resultObject.getBoolean("success")) {
            log.error("post path:{};params:{};errMsg:{}", DaHuaIccConstant.CREATE_USER_URL, JSON.toJSONString(params), resultObject.getString("errMsg"));
            throw new BusinessException(resultObject.getString("errMsg"));
        }
        AuthAccountMapping authAccountMapping = new AuthAccountMapping();
        String data = resultObject.getString("data");
        authAccountMapping.setOpenId(data);
        authAccountMapping.setOpenCode(userDaHuaDTO.getCode());
        return authAccountMapping;
    }

    public AuthAccountMapping queryUser(Account account, VisitorIntegrationConfigDTO configDTO) {
        AuthAccountMapping authAccountMapping = null;
        HashMap<String, Object> params = new HashMap<>();
        params.put("searchKey", account.getPhone());
        params.put("pageNum", 1);
        params.put("pageSize", 10);
        JSONObject resultObject = generalDaHuaIccHandler.post(DaHuaIccConstant.QUERY_USER_URL, params, configDTO.getProjectId(), configDTO.getProductId(), configDTO.getIpAndPort(), configDTO.getLoginName(), configDTO.getPassword(), configDTO.getAk(), configDTO.getSk());
        if (resultObject == null || !resultObject.getBoolean("success")) {
            log.error("post path:{};params:{};errMsg:{}", DaHuaIccConstant.QUERY_USER_URL, JSON.toJSONString(params), resultObject.getString("errMsg"));
            return null;
        }
        JSONObject data = resultObject.getJSONObject("data");
        JSONArray pageData = data.getJSONArray("pageData");
        if (!pageData.isEmpty()) {
            JSONObject object = (JSONObject) pageData.get(0);
            UserDaHuaDTO userDaHuaDTO = object.toJavaObject(UserDaHuaDTO.class);
            authAccountMapping = new AuthAccountMapping();
            authAccountMapping.setOpenId(userDaHuaDTO.getId());
            authAccountMapping.setOpenCode(userDaHuaDTO.getCode());
        }
        return authAccountMapping;

    }

    /**
     * 预约授权
     *
     * @param configDTO
     * @param infoDTO
     * @return
     */
    public VisitorOpenDTO createVisitorAuth(VisitorIntegrationConfigDTO configDTO, VisitorInfoDaHuaDTO infoDTO) {
        log.warn("访客预约集成配置为：{}",configDTO);
        Map<String, Object> params = JSONObject.parseObject(JSONObject.toJSONString(infoDTO), Map.class);
        // 处理时间格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date v_timeStr = new Date((long) params.get("v_timeStr"));
        Date v_lvTimeStr = new Date((long) params.get("v_lvTimeStr"));
        params.put("v_timeStr", sdf.format(v_timeStr));
        params.put("v_lvTimeStr", sdf.format(v_lvTimeStr));
        // 访客预约
        JSONObject resultObject = generalDaHuaIccHandler.post(DaHuaIccConstant.VISITOR_APPOINTMENT, params, configDTO.getProjectId(), configDTO.getProductId(), configDTO.getIpAndPort(), configDTO.getLoginName(), configDTO.getPassword(), configDTO.getAk(), configDTO.getSk());
        if (resultObject == null || !resultObject.getBoolean("success")) {
            log.error("post path:{};params:{};errMsg:{}", DaHuaIccConstant.VISITOR_APPOINTMENT, JSON.toJSONString(params), resultObject.getString("errMsg"));
        }
        log.warn("调用大华预约接口返回{}",resultObject);
        VisitorOpenDTO commonDTO = new VisitorOpenDTO();
        commonDTO.setOpenId(resultObject.getJSONObject("data").getString("id"));
        commonDTO.setQrCode(resultObject.getJSONObject("data").getString("v_barCode"));
        commonDTO.setAppointmentCode(resultObject.getJSONObject("data").getString("appointmentCode"));
        return commonDTO;
    }

    public JSONObject getVisitorInfoByIdCard(VisitorIntegrationConfigDTO configDTO, VisitorInfoDaHuaDTO infoDTO) {
        String api = DaHuaIccConstant.APPOINTMENT_BY_CERTIFICATE_NUMBER + infoDTO.getV_certificateNumber();
        JSONObject resultObject = generalDaHuaIccHandler.get(api, new HashMap<>(), configDTO.getProjectId(), configDTO.getProductId(),
                configDTO.getIpAndPort(), configDTO.getLoginName(), configDTO.getPassword(), configDTO.getAk(),
                configDTO.getSk());
        if (resultObject == null) {
            throw new BusinessException("大华ICC-getVisitorInfo返回为null");
        } else {
            if (!resultObject.getBoolean("success")) {
                log.error("大华ICC-getVisitorInfo path:{}, errMsg:{}", DaHuaIccConstant.VISITOR_APPOINTMENT, resultObject.getString("errMsg"));
                throw new BusinessException("大华ICC-getVisitorInfo异常");
            } else {
                return resultObject.getJSONObject("data");
            }
        }
    }

    public JSONObject getVisitorInfoByAppointmentCode(VisitorIntegrationConfigDTO configDTO, String appointmentCode) {
        String api = DaHuaIccConstant.APPOINTMENT_BY_APPOINTMENT_CODE + appointmentCode;
        String successCode = "success";
        Integer projectId = configDTO.getProjectId();
        Integer productId = configDTO.getProductId();
        JSONObject resultObject = generalDaHuaIccHandler.get(api,new HashMap<>(), projectId,productId ,
                configDTO.getIpAndPort(), configDTO.getLoginName(), configDTO.getPassword(), configDTO.getAk(),
                configDTO.getSk());
        if (resultObject == null) {
            return null;
        }
        if (!resultObject.getBoolean(successCode)) {
            log.error("大华根据预约码获取访客信息失败, errMsg:{}",resultObject.getString("errMsg"));
        }
        return resultObject.getJSONObject("data");
    }

    public Map<String,List<String>> getVisitorAreaInfo(VisitorIntegrationConfigDTO configDTO){
        Map<String,List<String>> openDeviceInfoMap = new HashMap<>();
        Map<String, Object> params = new HashMap<>();
        params.put("pageNumber",1);
        params.put("pageSize",20);
        JSONObject resultObject = generalDaHuaIccHandler.post(DaHuaIccConstant.VISITOR_AREA_PAGE, params, configDTO.getProjectId(), configDTO.getProductId(), configDTO.getIpAndPort(), configDTO.getLoginName(), configDTO.getPassword(), configDTO.getAk(), configDTO.getSk());
        if (resultObject == null || !resultObject.getBoolean("success")) {
            log.error("post path:{};params:{};errMsg:{}", DaHuaIccConstant.VISITOR_AREA_PAGE, JSON.toJSONString(params), resultObject.getString("errMsg"));
        }
        log.warn("调用大华ICC区域分页返回{}",resultObject);
        JSONArray jsonArray = resultObject.getJSONObject("data").getJSONArray("pageData");
        for(int i=0;i<jsonArray.size();i++) {
            String areaId = jsonArray.getJSONObject(i).getString("id");
            String api = DaHuaIccConstant.VISITOR_AREA_DETAIL + areaId;
            JSONObject jsonDetail = generalDaHuaIccHandler.get(api, new HashMap<>(), configDTO.getProjectId(), configDTO.getProductId(),
                    configDTO.getIpAndPort(), configDTO.getLoginName(), configDTO.getPassword(), configDTO.getAk(),
                    configDTO.getSk());
            if (resultObject == null || !resultObject.getBoolean("success")) {
                log.error("post path:{};params:{};errMsg:{}", api, JSON.toJSONString(params), resultObject.getString("errMsg"));
            }
            JSONArray array = jsonDetail.getJSONObject("data").getJSONArray("accessChannel");
            List<String> accessChannel = array.stream().map(item -> ((JSONObject) item).getString("channelName")).collect(Collectors.toList());
            openDeviceInfoMap.put(areaId,accessChannel);
        }
        return  openDeviceInfoMap;
    }

    /**
     * 取消预约授权
     *
     * @param configDTO
     * @param infoDTO
     * @return
     */
    public ResultJson deleteVisitorAuth(VisitorIntegrationConfigDTO configDTO, VisitorInfoDTO infoDTO) {
        // 根据访客身份证获取访客预约信息
        if (!StringUtils.isEmpty(infoDTO.getOpenId())) {
            // 访客预约取消
            HashMap<String, Object> params = new HashMap<>(2);
            params.put("ids", infoDTO.getOpenId());
            params.put("status", DaHuaIccConstant.DAHUA_DELETE_BOOK);
            JSONObject resultObject = generalDaHuaIccHandler.post(DaHuaIccConstant.VISITOR_DELETE_BOOK_URL, params, configDTO.getProjectId(), configDTO.getProductId(), configDTO.getIpAndPort(), configDTO.getLoginName(), configDTO.getPassword(), configDTO.getAk(), configDTO.getSk());
            if (resultObject == null || !resultObject.getBoolean("success")) {
                log.error("post path:{};params:{};errMsg:{}", DaHuaIccConstant.VISITOR_DELETE_BOOK_URL, JSON.toJSONString(params), resultObject.getString("errMsg"));
                return ResultJson.fail(resultObject.getString("errMsg"));
            }
            return ResultJson.success(CodeEnum.SUCCESS.description, resultObject.getString("data"));
        }
        else {
            log.error("没有访客预约信息");
            return ResultJson.fail("没有访客预约信息");
        }
    }

    public VisitorInfoDTO getVisitorAccessRecord(VisitorIntegrationConfigDTO configDTO, VisitorAuthDTO dto){
        LocalDateTime ldt1 = LocalDateTimeUtils.convertDateToLDT(dto.getAuthStartTime());
        LocalDateTime ldt2 = LocalDateTimeUtils.convertDateToLDT(dto.getAuthEndTime());
        String startTime = LocalDateTimeUtils.formatTime(ldt1,LocalDateTimeUtils.DATE_TIME);
        String endTime = LocalDateTimeUtils.formatTime(ldt2,LocalDateTimeUtils.DATE_TIME);
        HashMap<String, Object> params = new HashMap<>(2);
        params.put("pageNum",1);
        params.put("pageSize",20);
        params.put("v_name",dto.getName());
        params.put("v_phone",dto.getPhone());
        params.put("comeVisit_startTime",startTime);
        params.put("comeVisit_endTime",endTime);
        JSONObject resultObject = generalDaHuaIccHandler.post(DaHuaIccConstant.VISITOR_ACCESS_RECORD,
                params, configDTO.getProjectId(), configDTO.getProductId(), configDTO.getIpAndPort(),
                configDTO.getLoginName(), configDTO.getPassword(), configDTO.getAk(), configDTO.getSk());
        log.info("params{},resultObject{}",params,resultObject);
        if (resultObject == null || !resultObject.getBoolean("success")) {
            if (null != resultObject){
                log.error("post 获取访客通行记录;params:{};errMsg:{}",params,resultObject.getString("errMsg"));
            }
            return new VisitorInfoDTO();
        }
        VisitorInfoDTO infoDTO = new VisitorInfoDTO();
        JSONArray dataArray = resultObject.getJSONObject("data").getJSONArray("pageData");
        if (dataArray.isEmpty()){
            return new VisitorInfoDTO();
        }
        JSONObject object = dataArray.getJSONObject(0);
        log.info("访客通行记录{}",object);
        infoDTO.setName(object.getString("v_name"));
        infoDTO.setPhone(object.getString("v_phone"));
        Integer status = object.getInteger("status");
        if (status.equals(DaHuaIccConstant.ARRIVE)) {
            infoDTO.setStatus(VisitorStatusEnum.ARRIVED);
        }
        if (status.equals(DaHuaIccConstant.LEAVE)) {
            infoDTO.setStatus(VisitorStatusEnum.LEAVE);
        }
        return infoDTO;
    }

    /**
     * 下发二维码
     *
     * @param configDTO
     * @return
     */
    public ResultJson getQrCode(VisitorIntegrationConfigDTO configDTO, VisitorAuthDTO visitorAuthDTO) {
        //大华二维码有效期暂定为当天晚上24点
        Date startDate = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String startTime = simpleDateFormat.format(startDate);
        String dateStr = startTime.split(" ")[0];
        String endTime = dateStr + " 23:59:59";
        HashMap<String, Object> params = new HashMap<>();
        params.put("v_phone", visitorAuthDTO.getPhone());
        params.put("v_certificateType", CredentialsEnum.findEnumByCode(visitorAuthDTO.getIdentityCardType().shortValue()).getDescription());
        params.put("v_certificateNumber", visitorAuthDTO.getIdentityCard());
        params.put("v_reason", visitorAuthDTO.getSubjectMatter());
        int count = 1;
        if (!CollectionUtils.isEmpty(visitorAuthDTO.getFollowerList())) {
            count = count + visitorAuthDTO.getFollowerList().size();
        }
        params.put("v_personSum", count);
        params.put("v_name", visitorAuthDTO.getName());
        params.put("v_dw", "访客单位");
        params.put("v_timeStr", startTime);
        params.put("v_lvTimeStr", endTime);
        params.put("isvCode", visitorAuthDTO.getIntervieweeOpenId());
        params.put("isAuthIPMS", (StringUtils.isEmpty(visitorAuthDTO.getCarNum()) ? 0 : 1));
        params.put("accessChannels", visitorAuthDTO.getOpenDeviceIdList());
        JSONObject resultObject = generalDaHuaIccHandler.post(DaHuaIccConstant.QR_CODE_URL, params, configDTO.getProjectId(), configDTO.getProductId(), configDTO.getIpAndPort(), configDTO.getLoginName(), configDTO.getPassword(), configDTO.getAk(), configDTO.getSk());
        if (resultObject == null || !resultObject.getBoolean("success")) {
            log.error("post path:{};params:{};errMsg:{}", DaHuaIccConstant.QR_CODE_URL, JSON.toJSONString(params), resultObject.getString("errMsg"));
            return ResultJson.fail(resultObject.getString("errMsg"));
        }
        JSONObject data = JSONObject.parseObject(resultObject.getString("data"));
        log.warn("大华获取的二维码:{}",resultObject.getString("data"));
        return ResultJson.success(CodeEnum.SUCCESS.description, data.getString("qrCode"));
    }


    public String getVisitorImageUrl(VisitorIntegrationConfigDTO configDTO, VisitorAuthDTO visitorAuthDTO) {
        if (com.xhwl.common.utils.StringUtils.isEmpty(visitorAuthDTO.getFaceUrl())) {
            return null;
        }
        HashMap<String, Object> params = new HashMap<>(1);
        params.put("imageUrl", visitorAuthDTO.getFaceUrl());
        JSONObject resultObject = generalDaHuaIccHandler.upload(DaHuaIccConstant.UPLOAD_IMAGE_URL, params, configDTO.getProjectId(), configDTO.getProductId(), configDTO.getIpAndPort(), configDTO.getLoginName(), configDTO.getPassword(), configDTO.getAk(), configDTO.getSk());
        if (resultObject == null || !resultObject.getBoolean("success")) {
            log.error("post path:{};params:{};errMsg:{}", DaHuaIccConstant.GENERATE_USER_URL, JSON.toJSONString(params), resultObject.getString("errMsg"));
            return null;
        }
        return resultObject.getJSONObject("data").getString("fileUrl");
    }

    public String getFollowerImageUrl(VisitorIntegrationConfigDTO configDTO, Follower follower) {
        if (follower.getFaceUrl() == null) {
            return null;
        }
        HashMap<String, Object> params = new HashMap<>(1);
        params.put("imageUrl", follower.getFaceUrl());
        JSONObject resultObject = generalDaHuaIccHandler.upload(DaHuaIccConstant.UPLOAD_IMAGE_URL, params, configDTO.getProjectId(), configDTO.getProductId(), configDTO.getIpAndPort(), configDTO.getLoginName(), configDTO.getPassword(), configDTO.getAk(), configDTO.getSk());
        if (resultObject == null || !resultObject.getBoolean("success")) {
            log.error("post path:{};params:{};errMsg:{}", DaHuaIccConstant.GENERATE_USER_URL, JSON.toJSONString(params), resultObject.getString("errMsg"));
            return null;
        }
        return resultObject.getJSONObject("data").getString("fileUrl");
    }

    public String handleOssWay(VisitorIntegrationConfigDTO configDTO, String uri) {
        SecurityDaHuaDTO securityDaHuaDTO = generalDaHuaIccHandler.getToken(configDTO.getProjectId(), configDTO.getProductId(), configDTO.getIpAndPort(), configDTO.getLoginName(), configDTO.getPassword(), configDTO.getAk(), configDTO.getSk());
        String prefix = configDTO.getIpAndPort() + DaHuaIccConstant.OSS;
        String suffix = "?token=" + securityDaHuaDTO.getToken();
        return prefix + uri + suffix;
    }
}
